package Parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.security.auth.Refreshable;

import DataModel.Feature;
import DataModel.LociHolder;
import DataModel.Locus;
import DataModel.Tupel;

/**
 * Parses a fasta file
 * 
 * @author Stefan Lorenz <br>
 *         <b>Date:</b> 12.11.2012
 */
public class ParseFastA {

	/**
	 * LociHolder wich represents the sequence
	 */
	private LociHolder lociHolder;
	/**
	 * Reader to read file
	 */
	private BufferedReader reader;

	/**
	 * The Constructor of the fastA parser. The sequence is represented as a
	 * {@link LociHolder} without {@link Feature} containing only the sequence.
	 * 
	 * @param fastaFile
	 *            File to parse
	 * @throws IOException
	 */
	public ParseFastA(File fastaFile, String reference, String range) throws IOException {

		reader = new BufferedReader(new FileReader(fastaFile));

		this.lociHolder = new LociHolder();
		this.lociHolder.setFile(fastaFile);

		String line = "";
		StringBuffer seq = new StringBuffer();
		boolean read = false;
		while ((line = reader.readLine()) != null) {
			if (line.contains(reference) && line.startsWith(">")) {
				Locus locus = new Locus();
				locus.setLocusName(line.substring(1));
				locus.setNameOfOrganism("NA");
				locus.setTypeOfLocus("NA");
				locus.setTypeOfSequence("NA");
				this.lociHolder.getListOfLoci().add(locus);
				read = true;
				continue;
			} else if (line.startsWith(">"))
				read = false;
			if (read) {
				seq.append(line.trim());
			}
		}
		Tupel tupel = getRangeToParseFromString(range);
		if(tupel.getStart() != -1 && tupel.getStop() != -1)
			seq = new StringBuffer(seq.subSequence(tupel.getStart(), tupel.getStop()));	
		
		// add last sequence to the locus and set type
		this.lociHolder.getListOfLoci().get(this.lociHolder.getListOfLoci().size() - 1).setSequence(seq);
		this.lociHolder.setTypeOfFile("fas");
	}

	/**
	 * Returns the LociHolder
	 * 
	 * @return the {@link LociHolder}
	 */
	public LociHolder getLociHolder() {
		return lociHolder;
	}

	/**
	 * parses an region string which must contain either "-" or ":" as seperator
	 * of two INTs
	 * 
	 * @param region
	 *            to load into browser
	 * @return
	 */
	private Tupel getRangeToParseFromString(String region) {
		String range = region.replace(" ", "");
		Tupel tupel = new Tupel(-1, -1);
		if (range.toLowerCase() != "complete") {
			// sort order
			int start = -1;
			int stop = -1;
			if (range.contains("-")) {
				start = Integer.parseInt(range.split("-")[0]);
				stop = Integer.parseInt(range.split("-")[1]);
			} else if (range.contains(":")) {
				start = Integer.parseInt(range.split(":")[0]);
				stop = Integer.parseInt(range.split(":")[1]);
			}
			tupel.setStart(Math.min(start, stop));
			tupel.setStop(Math.max(start, stop));
		}
		return tupel;
	}
}
